// 任务管理系统 - 主JavaScript文件

// 全局配置
const API_BASE_URL = '/api';

// 工具函数
const Utils = {
    // 显示加载状态
    showLoading: function(show, elementSelector) {
        if (typeof show === 'boolean') {
            // 全局加载状态
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (show) {
                if (!loadingOverlay) {
                    const overlay = document.createElement('div');
                    overlay.id = 'loadingOverlay';
                    overlay.className = 'loading-overlay';
                    overlay.innerHTML = '<div class="loading-spinner"><span class="loading"></span> 加载中...</div>';
                    document.body.appendChild(overlay);
                }
            } else {
                if (loadingOverlay) {
                    loadingOverlay.remove();
                }
            }
        } else if (show) {
            // 元素级加载状态（兼容旧版本）
            const element = typeof show === 'string' ? document.querySelector(show) : show;
            if (element) {
                element.innerHTML = '<span class="loading"></span> 加载中...';
                element.disabled = true;
            }
        }
        
        // 按钮级加载状态
        if (elementSelector) {
            const element = document.querySelector(elementSelector);
            if (element) {
                if (show) {
                    element.innerHTML = '<span class="loading"></span> 处理中...';
                    element.disabled = true;
                } else {
                    element.innerHTML = element.getAttribute('data-original-text') || '提交';
                    element.disabled = false;
                }
            }
        }
    },

    // 隐藏加载状态
    hideLoading: function(element, originalText) {
        if (element) {
            element.innerHTML = originalText;
            element.disabled = false;
        }
    },

    // 显示消息提示
    showMessage: function(message, type = 'info') {
        // 兼容性处理
        if (type === 'error') type = 'danger';
        
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            <i class="bi bi-${type === 'success' ? 'check-circle' : type === 'danger' ? 'exclamation-triangle' : 'info-circle'}"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        const container = document.querySelector('main .container');
        if (container) {
            container.insertBefore(alertDiv, container.firstChild);
            
            // 自动隐藏
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
    },

    // 格式化日期
    formatDate: function(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    },

    // 格式化状态
    formatStatus: function(status) {
        const statusMap = {
            'TODO': { text: '待办', class: 'status-todo' },
            'IN_PROGRESS': { text: '进行中', class: 'status-in-progress' },
            'PAUSED': { text: '暂停', class: 'status-paused' },
            'COMPLETED': { text: '已完成', class: 'status-completed' },
            'CANCELLED': { text: '已取消', class: 'status-cancelled' },
            'ACTIVE': { text: '活跃', class: 'status-in-progress' },
            'INACTIVE': { text: '非活跃', class: 'status-paused' }
        };
        
        const statusInfo = statusMap[status] || { text: status, class: 'status-todo' };
        return `<span class="badge ${statusInfo.class}">${statusInfo.text}</span>`;
    },

    // 格式化优先级
    formatPriority: function(priority) {
        const priorityMap = {
            'LOW': { text: '低', class: 'priority-low' },
            'MEDIUM': { text: '中', class: 'priority-medium' },
            'HIGH': { text: '高', class: 'priority-high' },
            'URGENT': { text: '紧急', class: 'priority-urgent' }
        };
        
        const priorityInfo = priorityMap[priority] || { text: priority, class: 'priority-medium' };
        return `<span class="badge ${priorityInfo.class}">${priorityInfo.text}</span>`;
    },

    // 格式化进度
    formatProgress: function(progress) {
        const percentage = Math.round(progress || 0);
        let progressClass = 'bg-info';
        
        if (percentage >= 100) {
            progressClass = 'bg-success';
        } else if (percentage >= 75) {
            progressClass = 'bg-primary';
        } else if (percentage >= 50) {
            progressClass = 'bg-warning';
        }
        
        return `
            <div class="progress" style="height: 20px;">
                <div class="progress-bar ${progressClass}" role="progressbar" 
                     style="width: ${percentage}%" aria-valuenow="${percentage}" 
                     aria-valuemin="0" aria-valuemax="100">
                    ${percentage}%
                </div>
            </div>
        `;
    }
};

// API 请求封装
const API = {
    // 通用请求方法
    request: async function(url, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        };
        
        const finalOptions = { ...defaultOptions, ...options };
        
        try {
            const response = await fetch(API_BASE_URL + url, finalOptions);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return await response.json();
            } else {
                return await response.text();
            }
        } catch (error) {
            console.error('API request failed:', error);
            throw error;
        }
    },

    // GET 请求
    get: function(url) {
        return this.request(url, { method: 'GET' });
    },

    // POST 请求
    post: function(url, data) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },

    // PUT 请求
    put: function(url, data) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },

    // DELETE 请求
    delete: function(url) {
        return this.request(url, { method: 'DELETE' });
    }
};

// 表单处理
const FormHandler = {
    // 序列化表单数据
    serialize: function(form) {
        const formData = new FormData(form);
        const data = {};
        
        for (let [key, value] of formData.entries()) {
            data[key] = value;
        }
        
        return data;
    },

    // 验证表单
    validate: function(form) {
        const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');
        let isValid = true;
        
        inputs.forEach(input => {
            if (!input.value.trim()) {
                input.classList.add('is-invalid');
                isValid = false;
            } else {
                input.classList.remove('is-invalid');
            }
        });
        
        return isValid;
    },

    // 重置表单
    reset: function(form) {
        form.reset();
        const inputs = form.querySelectorAll('.is-invalid');
        inputs.forEach(input => {
            input.classList.remove('is-invalid');
        });
    }
};

// 模态框处理
const ModalHandler = {
    // 显示模态框
    show: function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            return bsModal;
        }
    },

    // 隐藏模态框
    hide: function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            const bsModal = bootstrap.Modal.getInstance(modal);
            if (bsModal) {
                bsModal.hide();
            }
        }
    }
};

// 确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 初始化弹出框
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function(popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });

    // 为所有表单添加验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!FormHandler.validate(form)) {
                e.preventDefault();
                e.stopPropagation();
                Utils.showMessage('请填写所有必填字段', 'danger');
            }
        });
    });

    // 为所有删除按钮添加确认
    const deleteButtons = document.querySelectorAll('.btn-delete, [data-action="delete"]');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            confirmAction('确定要删除这个项目吗？此操作不可撤销。', () => {
                // 执行删除操作
                const url = button.getAttribute('href') || button.getAttribute('data-url');
                if (url) {
                    window.location.href = url;
                }
            });
        });
    });

    // 自动隐藏警告消息
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            if (alert.parentNode) {
                alert.classList.add('fade');
                setTimeout(() => {
                    alert.remove();
                }, 150);
            }
        }, 5000);
    });
});

// 更新面包屑导航
function updateBreadcrumb(title, path) {
    // 这是一个占位函数，实际项目中可以根据需要实现面包屑导航
    document.title = title + ' - 任务管理系统';
}

// 全局showLoading函数（兼容性）
function showLoading(show, elementSelector) {
    Utils.showLoading(show, elementSelector);
}

// 全局showMessage函数（兼容性）
function showMessage(message, type) {
    Utils.showMessage(message, type);
}

// API请求函数（兼容性函数）
function apiRequest(method, url, data = null) {
    const options = {
        method: method.toUpperCase(),
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    };
    
    if (data && (method.toUpperCase() === 'POST' || method.toUpperCase() === 'PUT')) {
        options.body = JSON.stringify(data);
    }
    
    return fetch(API_BASE_URL + url, options)
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    throw new Error(text || `HTTP error! status: ${response.status}`);
                });
            }
            
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return response.json();
            } else {
                return response.text();
            }
        });
}

// 导出到全局作用域
window.Utils = Utils;
window.API = API;
window.apiRequest = apiRequest;
window.FormHandler = FormHandler;
window.ModalHandler = ModalHandler;
window.confirmAction = confirmAction;